package cn.xiaobai.handler;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

/**
 * 消息处理器
 *
 * @Author yangdaji
 * @Date 2023/12/24
 * @PackageName cn.xiaobai.handler
 * @ClassName MsgHandler
 */
public class MsgHandler extends Handler {

    private cn.xiaobai.domain.Message message;

    private Context context;

    private AlertDialog alertDialog;

    private boolean type;

    public MsgHandler(Context context) {
        this(context, null);
    }

    public MsgHandler(Context context, cn.xiaobai.domain.Message message) {
        super(Looper.getMainLooper());
        this.context = context;
        this.message = message;
        this.alertDialog = new AlertDialog.Builder(context).create();
    }

    /**
     * 发送消息
     *
     * @param type true: 使用短消息弹框, 否则使用对话框
     */
    public void sendMsg(Boolean type) {
        this.type = type;
        sendMessage(new Message());
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        if (type) {
            Toast.makeText(context, getMessage(), Toast.LENGTH_LONG).show();
        } else {
            alertDialog.setMessage(getMessage());
            alertDialog.show();
        }
    }

    public String getMessage() {
        return message != null ? message.getMsg() : null;
    }

    public void setMessage(cn.xiaobai.domain.Message message) {
        this.message = message;
    }
}
